package com.itfitness.calendarview.widget

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.itfitness.calendarview.R
import com.itfitness.calendarview.adapter.CalendarFragmentAdapter
import com.itfitness.calendarview.fragment.CalendarFragment
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs

/**
 *
 * @Description:     java类作用描述
 * @Author:         作者名
 * @CreateDate:     2022/2/14 15:59
 * @UpdateUser:     更新者：
 * @UpdateDate:     2022/2/14 15:59
 * @UpdateRemark:   更新说明：
 */
class CalendarView:FrameLayout {
    //保存选择的日期
    companion object SelectDate {
        var SELECT_YEAR = 0 //选择的年
        var SELECT_MONTH = 0 //选择的月
        var SELECT_DAY = 0 //选择的日
    }
    private lateinit var vpContainer:ViewPager2
    private var fragmentAdapter:CalendarFragmentAdapter? = null
    private val fragments:ArrayList<CalendarFragment> = ArrayList()
    private var currentPos = 0
    private val offsetItem = 200 //前面偏移的页数
    var onDateSelectCallBack:OnDateSelectCallBack? = null
    var onPageChangedCallBack:OnPageChangedCallBack? = null
        set(value) {
            //赋值的时候回调下当前的年月
            val currentMonth = Calendar.getInstance().get(Calendar.MONTH)
            val currentYear = Calendar.getInstance().get(Calendar.YEAR)
            field = value
            //展示的月需要加1（因为系统中的月是从0开始的）
            field?.onPageChanged(currentYear,currentMonth + 1)
        }
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr){
        View.inflate(context, R.layout.view_calendar,this)
        initView()
        initFragments()
        initListener()
    }

    private fun initListener(){
        vpContainer.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                currentPos = position
                fragments[currentPos].arguments?.let {
                    val currentPageYear = it.getInt(CalendarFragment.YEAR) //当前页的年
                    val currentPageMonth = it.getInt(CalendarFragment.MONTH) //当前页的月
                    //展示的月需要加1（因为系统中的月是从0开始的）
                    onPageChangedCallBack?.onPageChanged(currentPageYear,currentPageMonth + 1)
                }
                //刷新下当前的数据
                fragments[currentPos].refreshData()
                if(currentPos + 3 > fragments.size){
                    addNextFragment()
                }
            }
        })
    }

    /**
     * 动态添加后面的日历
     */
    private fun addNextFragment() {
        fragments[fragments.size-1].arguments?.let {
            //获取展示的最小的年和月
            val minYear = it.getInt(CalendarFragment.YEAR)
            val minMonth = it.getInt(CalendarFragment.MONTH)
            //动态加两个
            for(i in minMonth + 1 until minMonth + 2){
                var month = i
                var year = minYear
                if(i > 11){
                    month = i - 12
                    year = minYear + 1
                }
                val fragment = CalendarFragment(object :OnDateSelectCallBack{
                    override fun onDateSelect(year: Int, month: Int, day: Int) {
                        onDateSelectCallBack?.onDateSelect(year,month,day)
                    }
                })
                val arguments = Bundle()
                arguments.putInt(CalendarFragment.YEAR,year)
                arguments.putInt(CalendarFragment.MONTH,month)
                fragment.arguments = arguments
                fragments.add(fragment)
            }
            fragmentAdapter?.notifyDataSetChanged()
        }
    }

    private fun initView() {
        vpContainer = findViewById(R.id.vpContainer)
    }

    private fun initFragments() {
        fragments.clear()
        val currentMonth = Calendar.getInstance().get(Calendar.MONTH)
        val currentYear = Calendar.getInstance().get(Calendar.YEAR)
        val currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
        SELECT_YEAR = currentYear
        SELECT_MONTH = currentMonth
        SELECT_DAY = currentDay
        for(i in currentMonth - offsetItem until currentMonth){
            var month = i
            var year = currentYear
            if(i < 0){
                month = 12 - abs(i)
                year = currentYear - 1
            }
            val fragment = CalendarFragment(object :OnDateSelectCallBack{
                override fun onDateSelect(year: Int, month: Int, day: Int) {
                    onDateSelectCallBack?.onDateSelect(year,month,day)
                }
            })
            val arguments = Bundle()
            arguments.putInt(CalendarFragment.YEAR,year)
            arguments.putInt(CalendarFragment.MONTH,month)
            fragment.arguments = arguments
            fragments.add(fragment)
        }
        //后面的默认多出5页，然后随着页面滑动来动态增加页数
        for(i in currentMonth..currentMonth + 5){
            var month = i
            var year = currentYear
            if(i > 11){
                month = i - 12
                year = currentYear + 1
            }
            val fragment = CalendarFragment(object :OnDateSelectCallBack{
                override fun onDateSelect(year: Int, month: Int, day: Int) {
                    onDateSelectCallBack?.onDateSelect(year,month,day)
                }
            })
            val arguments = Bundle()
            arguments.putInt(CalendarFragment.YEAR,year)
            arguments.putInt(CalendarFragment.MONTH,month)
            fragment.arguments = arguments
            fragments.add(fragment)
        }
        currentPos = fragments.size - 6
        if(context is FragmentActivity){
            val activity = context as FragmentActivity
            fragmentAdapter = CalendarFragmentAdapter(activity,fragments)
            vpContainer.adapter = fragmentAdapter
            vpContainer.setCurrentItem(currentPos,false)
        }
    }


    /**
     * 页面切换的监听
     */
    interface OnPageChangedCallBack{
        fun onPageChanged(year:Int,month:Int)
    }

    /**
     * 日期选择的回调
     */
    interface OnDateSelectCallBack{
        fun onDateSelect(year:Int,month:Int,day:Int)
    }
}